package com.yeyv.net.Web.Control.Anonymous;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.yeyv.net.Annotation.ControllerApi.AnonController;
import com.yeyv.net.UsefulEntity.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.HashMap;

@AnonController("/ai/baidu")
public class BaiduAIController {
    @Value("${ai.baidu.api-key}")
    public String apiKey;
    @Value("${ai.baidu.secret-key}")
    public String secretKey;
    final String rKEY = "Yv-AI-Baidu-Token";
    @Autowired
    RedisUtil redisUtil;

    public String getToken(){
//        if(redisUtil.hasKey(rKEY)){
//            return (String) redisUtil.get(rKEY);
//        }
        return requestToken();
    }

    public String requestToken() {
        HashMap<String, Object> form = new HashMap<>();
        form.put("grant_type", "client_credentials");
        form.put("client_id", apiKey);
        form.put("client_secret", secretKey);
        var body = HttpUtil
                .createPost(
                        "https://aip.baidubce.com/oauth/2.0/token?"
                                + HttpUtil.toParams(form))
                .header("Content-Type", "application/json")
                .execute()
                .body();
        JSONObject result = JSONObject.parseObject(body);
        if (result.containsKey("error")) {
            throw new RuntimeException(result.getString("error_description"));
        }
        var resp = result.getString("access_token");
        redisUtil.set(rKEY,resp);
        return resp;
    }

    @GetMapping("/4D0")
    //发送ERNIE-Bot 4.0请求
    public String postBot4D0() {
        HashMap<String, Object> form = new HashMap<>();
        JSONObject object = new JSONObject();
        object.put("role", "user");
        object.put("content", "你好");
        JSONArray array = new JSONArray();
        array.add(object);
        JSONObject body = new JSONObject();
        body.put("messages", array);
        var result = HttpUtil
                .createPost("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-4.0-turbo-128k?access_token=" + getToken())
                .header("Content-Type", "application/json")
                .body(body.toString())
                .execute();
        var text = result.body();
        System.out.println(text);
        return null;
    }
}
